<?php
session_start();

// 检查是否已安装
if (!file_exists(__DIR__ . '/config/config.php')) {
    header('Location: install.php');
    exit;
}

require_once __DIR__ . '/config/config.php';

// 检查用户是否已登录
$is_logged_in = isset($_SESSION['user_logged_in']) && $_SESSION['user_logged_in'];
$username = $_SESSION['username'] ?? '';

// 如果用户未登录，重定向到登录/注册页面
if (!$is_logged_in) {
    header('Location: login.php');
    exit;
}

// 获取用户数据目录
$user_dir = __DIR__ . '/users/' . $username;
if (!file_exists($user_dir)) {
    mkdir($user_dir, 0755, true);
}

// 获取历史聊天记录
$history_file = $user_dir . '/history.json';
$history = [];
if (file_exists($history_file)) {
    $history = json_decode(file_get_contents($history_file), true) ?: [];
}

// 获取用户提示词
$user_prompt_file = $user_dir . '/prompt.txt';
$user_prompt = file_exists($user_prompt_file) ? file_get_contents($user_prompt_file) : 'You are a helpful assistant.';

// 处理API请求
if ($_POST) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'delete_message') {
        $index = (int)$_POST['index'];
        if (isset($history[$index])) {
            unset($history[$index]);
            $history = array_values($history); // 重新索引
            file_put_contents($history_file, json_encode($history, JSON_PRETTY_PRINT));
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => '消息不存在']);
        }
        exit;
    } elseif ($action === 'edit_message') {
        $index = (int)$_POST['index'];
        $new_content = $_POST['content'] ?? '';
        if (isset($history[$index]) && !empty($new_content)) {
            $history[$index]['content'] = $new_content;
            file_put_contents($history_file, json_encode($history, JSON_PRETTY_PRINT));
            echo json_encode(['success' => true, 'content' => $new_content]);
        } else {
            echo json_encode(['success' => false, 'error' => '无效的消息或内容']);
        }
        exit;
    } elseif ($action === 'update_prompt') {
        $new_prompt = $_POST['prompt'] ?? '';
        if (!empty($new_prompt)) {
            // 保存到用户文件
            file_put_contents($user_prompt_file, $new_prompt);
            echo json_encode(['success' => true, 'prompt' => $new_prompt]);
        } else {
            echo json_encode(['success' => false, 'error' => '提示词不能为空']);
        }
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>lanxAI - 首个览星自研发AI</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
    <div class="header">
     <h1>lanxAI - 首个览星自研发AI</h1>
        <div class="user-info" style="position: absolute; top: 15px; left: 15px; color: white; font-size: 14px;">
            欢迎, <?php echo htmlspecialchars($_SESSION['user_nickname'] ?? $_SESSION['username']); ?>!<a href='login.php'><button class="active">登陆</button></a>
        </div>
        <div class="language-switch">
            <button id="zh-btn" class="active">中文</button>
            <button id="en-btn">English</button>
        </div>
    </div>
    
    <div class="chat-container">
        <div class="chat-history" id="chat-history">
            <?php foreach ($history as $index => $item): ?>
                <div class="message <?php echo $item['role'] === 'user' ? 'user-message' : 'ai-message'; ?>" data-index="<?php echo $index; ?>">
                    <div class="message-header">
                        <strong><?php echo $item['role'] === 'user' ? '您' : 'AI'; ?>:</strong>
                        <div class="message-actions">
                            <button class="edit-btn" onclick="editMessage(<?php echo $index; ?>)">编辑</button>
                            <button class="delete-btn" onclick="deleteMessage(<?php echo $index; ?>)">删除</button>
                        </div>
                    </div>
                    <div class="message-content" id="content-<?php echo $index; ?>">
                        <?php echo htmlspecialchars($item['content']); ?>
                    </div>
                    <small class="message-time"><?php echo $item['timestamp']; ?></small>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div class="input-container">
            <textarea id="message-input" placeholder="输入您的消息..."></textarea>
            <div class="input-controls">
                <button id="send-btn">发送</button>
                <input type="text" id="prompt-input" placeholder="AI提示词..." value="<?php echo htmlspecialchars($user_prompt); ?>">
                <button id="update-prompt-btn">更新提示词</button>
            </div>
        </div>
    </div>
    
    <div class="footer">
        LANX开源AI
    </div>

    <script>
        const chatHistory = document.getElementById('chat-history');
        const messageInput = document.getElementById('message-input');
        const sendBtn = document.getElementById('send-btn');
        const promptInput = document.getElementById('prompt-input');
        const updatePromptBtn = document.getElementById('update-prompt-btn');
        
        // 自动滚动到底部
        chatHistory.scrollTop = chatHistory.scrollHeight;
        
        // 发送消息函数
        function sendMessage() {
            const message = messageInput.value.trim();
            const userPrompt = promptInput.value.trim() || 'You are a helpful assistant.';
            
            if (!message) return;
            
            // 添加用户消息到界面
            addMessageToUI('user', message);
            
            // 清空输入框
            messageInput.value = '';
            
            // 发送请求到API
            fetch('api/chat.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `message=${encodeURIComponent(message)}&user_prompt=${encodeURIComponent(userPrompt)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    addMessageToUI('assistant', data.response);
                } else {
                    addMessageToUI('assistant', '错误: ' + data.error);
                }
            })
            .catch(error => {
                addMessageToUI('assistant', '错误: ' + error.message);
            });
        }
        
        // 添加消息到界面
        function addMessageToUI(role, content) {
            // 获取当前消息数量以确定新消息的索引
            const messageElements = document.querySelectorAll('.message');
            const newIndex = messageElements.length;
            
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${role === 'user' ? 'user-message' : 'ai-message'}`;
            messageDiv.dataset.index = newIndex;
            
            const roleText = role === 'user' ? '您' : 'AI';
            messageDiv.innerHTML = `
                <div class="message-header">
                    <strong>${roleText}:</strong>
                    <div class="message-actions">
                        <button class="edit-btn" onclick="editMessage(${newIndex})">编辑</button>
                        <button class="delete-btn" onclick="deleteMessage(${newIndex})">删除</button>
                    </div>
                </div>
                <div class="message-content" id="content-${newIndex}">
                    ${content}
                </div>
                <small class="message-time">${new Date().toLocaleString()}</small>
            `;
            
            chatHistory.appendChild(messageDiv);
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }
        
        // 删除消息
        function deleteMessage(index) {
            if (confirm('确定要删除这条消息吗？')) {
                fetch('', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `action=delete_message&index=${index}`
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 从界面移除消息元素
                        const messageElement = document.querySelector(`.message[data-index="${index}"]`);
                        if (messageElement) {
                            messageElement.remove();
                            
                            // 更新其他消息的索引
                            updateMessageIndexes();
                        }
                    } else {
                        alert('删除失败: ' + data.error);
                    }
                })
                .catch(error => {
                    alert('删除失败: ' + error.message);
                });
            }
        }
        
        // 编辑消息
        function editMessage(index) {
            const contentElement = document.getElementById(`content-${index}`);
            const currentContent = contentElement.textContent;
            
            const editInput = document.createElement('textarea');
            editInput.className = 'edit-input';
            editInput.value = currentContent;
            editInput.style.width = '100%';
            editInput.style.marginTop = '5px';
            editInput.style.padding = '5px';
            
            const saveBtn = document.createElement('button');
            saveBtn.textContent = '保存';
            saveBtn.className = 'save-edit-btn';
            saveBtn.style.marginTop = '5px';
            saveBtn.style.marginRight = '5px';
            saveBtn.onclick = () => saveEdit(index, editInput.value);
            
            const cancelBtn = document.createElement('button');
            cancelBtn.textContent = '取消';
            cancelBtn.className = 'cancel-edit-btn';
            cancelBtn.style.marginTop = '5px';
            cancelBtn.onclick = () => {
                contentElement.innerHTML = currentContent;
                contentElement.onclick = () => editMessage(index);
            };
            
            // 替换内容为编辑框
            contentElement.innerHTML = '';
            contentElement.appendChild(editInput);
            contentElement.appendChild(saveBtn);
            contentElement.appendChild(cancelBtn);
        }
        
        // 保存编辑
        function saveEdit(index, newContent) {
            if (!newContent.trim()) {
                alert('内容不能为空');
                return;
            }
            
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=edit_message&index=${index}&content=${encodeURIComponent(newContent)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const contentElement = document.getElementById(`content-${index}`);
                    contentElement.innerHTML = data.content;
                    contentElement.onclick = () => editMessage(index);
                } else {
                    alert('编辑失败: ' + data.error);
                }
            })
            .catch(error => {
                alert('编辑失败: ' + error.message);
            });
        }
        
        // 更新消息索引（在删除消息后重新分配索引）
        function updateMessageIndexes() {
            const messages = document.querySelectorAll('.message');
            messages.forEach((message, newIndex) => {
                message.dataset.index = newIndex;
                
                // 更新内容ID
                const contentElement = message.querySelector('.message-content');
                if (contentElement) {
                    contentElement.id = `content-${newIndex}`;
                }
                
                // 更新按钮的点击事件
                const editBtn = message.querySelector('.edit-btn');
                const deleteBtn = message.querySelector('.delete-btn');
                
                if (editBtn) {
                    editBtn.onclick = () => editMessage(newIndex);
                }
                if (deleteBtn) {
                    deleteBtn.onclick = () => deleteMessage(newIndex);
                }
            });
        }
        
        // 更新提示词
        function updatePrompt() {
            const newPrompt = promptInput.value.trim();
            if (!newPrompt) {
                alert('提示词不能为空');
                return;
            }
            
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `action=update_prompt&prompt=${encodeURIComponent(newPrompt)}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('提示词已更新');
                } else {
                    alert('更新失败: ' + data.error);
                }
            })
            .catch(error => {
                alert('更新失败: ' + error.message);
            });
        }
        
        // 事件监听
        sendBtn.addEventListener('click', sendMessage);
        
        messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        updatePromptBtn.addEventListener('click', updatePrompt);
        
        promptInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                updatePrompt();
            }
        });
        
        // 语言切换功能
        document.getElementById('zh-btn').addEventListener('click', function() {
            this.classList.add('active');
            document.getElementById('en-btn').classList.remove('active');
            // 这里可以添加实际的语言切换逻辑
        });
        
        document.getElementById('en-btn').addEventListener('click', function() {
            this.classList.add('active');
            document.getElementById('zh-btn').classList.remove('active');
            // 这里可以添加实际的语言切换逻辑
        });
    </script>
</body>
</html>
